from sanic.response import json,html
from sanic import Blueprint
from playhouse.shortcuts import model_to_dict
from model.model import TPost

rt = Blueprint("post",url_prefix="post")

# list
@rt.get("/")
def indexHandle(req):
    rows = TPost.select()
    res = []
    for m in rows:
        res.append(model_to_dict(m))
    return json({
            "msg":"this is book",
            "code":0,
            "data":res
    })

# add
@rt.post("/")
def indexHandle(req):
    rows = TPost.select()
    res = []
    for m in rows:
        res.append(model_to_dict(m))
    return json({
            "msg":"this is book",
            "code":0,
            "data":res
    })

# detail
@rt.get("/<id>")
def indexHandle(req,id):
    m = TPost.get_or_none(TPost.pid==id)
    res = m if (m is None) else model_to_dict(m)

    from mainapp import env
    tm = env.get_template("post/detail.html")
    s = tm.render(data=res)

    print("==========================")
    print(s)
    print("==========================")

    return html(s)

# update
@rt.post("/<id>")
def indexHandle(req,id):
    m = TPost.get_or_none(TPost.pid==id)
    res = m if (m is None) else model_to_dict(m)
    return json({
            "msg":"this is book",
            "code":0,
            "data":res
    })